package com.sinog.biz.config.logmongo;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import com.mongodb.BasicDBObject;
import com.sinog.biz.util.CodeUrlUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @desc mongodb适配器
 * @author lzq
 * @date 2021-04-13 12:19
 */
@Slf4j
@Component
@ConditionalOnProperty(name = "gkzx.azbj.log.mongodb", havingValue = "true")
public class MongoDbAppender extends UnsynchronizedAppenderBase<ILoggingEvent> implements ApplicationContextAware {

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static MongoTemplate mongoTemplate;

    /**
     * 描述
     * @param eventObject eventObject
     */
    @Override
    protected void append(ILoggingEvent eventObject) {
        if(null != mongoTemplate) {
            try {
                BasicDBObject doc = new BasicDBObject();
                LocalDateTime dateTime = LocalDateTime.ofEpochSecond(eventObject.getTimeStamp() / 1000L,0,ZoneOffset.ofHours(8));
                String time = dateTime.format(DATE_TIME_FORMATTER);
                doc.append("province_code",CodeUrlUtils.getLocalCode());
                doc.append("model","biz");
                doc.append("level",eventObject.getLevel().toString());
                doc.append("logger",eventObject.getLoggerName());
                doc.append("thread",eventObject.getThreadName());
                doc.append("message",eventObject.getFormattedMessage());
                doc.append("time",time);
                mongoTemplate.insert(doc,"azbj_biz_log");
            } catch(RuntimeException e) {
                log.error("发生异常:",e);
            }
        }
    }

    /**
     * 描述
     * @param applicationContext applicationContext
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        applicationContext.getAutowireCapableBeanFactory().getBean(MongoTemplate.class);
        mongoTemplate = applicationContext.getAutowireCapableBeanFactory().getBean(MongoTemplate.class);
    }
}